﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.Process
{
    public partial class UpdateProcessForm : DevExpress.XtraEditors.XtraForm
    {
        private Item editItem = null; // 要编辑的项目

        public UpdateProcessForm(Item itemToEdit)
        {
            InitializeComponent();
            editItem = itemToEdit;
            this.Text = "修改工序";
        }

        private void UpdateProcessForm_Load(object sender, EventArgs e)
        {
            // 在窗体加载时反显数据
            LoadEditData();
        }

        // 加载编辑数据到表单控件
        private void LoadEditData()
        {
            if (editItem != null)
            {
                try
                {
                    // 根据你的控件名称进行数据绑定
                    // 工序编码（只读）
                    if (Controls.Find("labelControl9", true).FirstOrDefault() is LabelControl lblProcessCode)
                    {
                        lblProcessCode.Text = editItem.ProcessCode;
                    }
                    
                    // 工序名称
                    if (Controls.Find("textEdit3", true).FirstOrDefault() is TextEdit txtProcessName)
                    {
                        txtProcessName.Text = editItem.ProcessName;
                    }
                    
                    // 是否启用
                    if (Controls.Find("radioGroup1", true).FirstOrDefault() is RadioGroup radioEnabled)
                    {
                        radioEnabled.EditValue = editItem.IsEnabled?true:false;
                    }
                    
                    // 准备时间
                    if (Controls.Find("textEdit1", true).FirstOrDefault() is TextEdit txtPrepTime)
                    {
                        txtPrepTime.Text = editItem.PreparationTime.ToString();
                    }
                    
                    // 生产时间
                    if (Controls.Find("textEdit4", true).FirstOrDefault() is TextEdit txtProdTime)
                    {
                        txtProdTime.Text = editItem.ProductionTime.ToString();
                    }
                    
                    // 工序说明
                    if (Controls.Find("textEdit2", true).FirstOrDefault() is TextEdit txtDescription)
                    {
                        txtDescription.Text = editItem.ProcessDescription;
                    }
                    
                    // 是否质检
                    if (Controls.Find("radioGroup6", true).FirstOrDefault() is RadioGroup radioQuality)
                    {
                        radioQuality.EditValue = editItem.IsQualityCheck ? true:false;
                    }
                    
                    // 备注
                    if (Controls.Find("memoEdit1", true).FirstOrDefault() is MemoEdit memoRemark)
                    {
                        memoRemark.Text = editItem.Remark;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载数据时发生异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // 关闭按钮事件
        private void CloseUpdateProcessSetUpClick(object sender, EventArgs e)
        {
            this.Close();
        }

        // 修改按钮事件
        private async void UpdateProcessSetUpClick(object sender, EventArgs e)
        {
            try
            {
                // 1. 收集表单数据
                var processData = new
                {
                    id = editItem.Id,
                    processCode = GetControlText("labelControl9"),
                    processName = GetControlText("textEdit3"),
                    isEnabled = Convert.ToBoolean(GetRadioValue("radioGroup1")),
                    preparationTime = Convert.ToDecimal(GetControlText("textEdit1")),
                    productionTime = Convert.ToDecimal(GetControlText("textEdit4")),
                    processDescription = GetControlText("textEdit2"),
                    isQualityCheck = Convert.ToBoolean(GetRadioValue("radioGroup6")),
                    remark = GetControlText("memoEdit1")
                };

                // 2. 验证必填字段
                if (string.IsNullOrWhiteSpace(processData.processName))
                {
                    MessageBox.Show("工序名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 3. 序列化为 JSON
                var json = JsonConvert.SerializeObject(processData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                // 4. 发送PUT请求
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:5053/");
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    var response = await client.PostAsync("api/ProcessManagement/UpdateProcessStepUp", content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("修改成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        string errorMessage = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"修改失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改过程中发生异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 辅助方法：获取控件文本
        private string GetControlText(string controlName)
        {
            try
            {
                var control = Controls.Find(controlName, true).FirstOrDefault();
                if (control is TextEdit textEdit)
                    return textEdit.Text.Trim();
                else if (control is MemoEdit memoEdit)
                    return memoEdit.Text.Trim();
                else if (control is LabelControl labelControl)
                    return labelControl.Text.Trim();
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        // 辅助方法：获取单选按钮值
        private string GetRadioValue(string controlName)
        {
            try
            {
                var control = Controls.Find(controlName, true).FirstOrDefault();
                if (control is RadioGroup radioGroup)
                    return radioGroup.EditValue?.ToString() ?? "0";
                return "0";
            }
            catch
            {
                return "0";
            }
        }

        // 重置按钮事件（可选）
        private void ResetUpdateProcessSetUpClick(object sender, EventArgs e)
        {
            LoadEditData(); // 重新加载原始数据
        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}